<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryRef"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <el-form-item label="手机号码" prop="tel">
        <el-input
          v-model="queryParams.tel"
          placeholder="请输入手机号码"
          clearable
          style="width: 240px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="创建时间" style="width: 308px">
        <el-date-picker
          v-model="dateRange"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
        :columns="columns"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="userList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="50" align="center" />
      <el-table-column
        label="编号"
        align="center"
        key="id"
        prop="id"
        v-if="columns[0].visible"
      />
      <el-table-column
        label="姓名"
        align="center"
        key="name"
        prop="name"
        v-if="columns[1].visible"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="电话"
        align="center"
        key="tel"
        prop="tel"
        v-if="columns[2].visible"
        width="120"
      />
      <el-table-column
        label="考试代码"
        align="center"
        key="examCode"
        prop="examCode"
        v-if="columns[3].visible"
      />
      <el-table-column
        label="积分"
        align="center"
        key="points"
        prop="points"
        v-if="columns[4].visible"
      />
      <el-table-column
        label="是否签到"
        align="center"
        key="hasSigned"
        v-if="columns[5].visible"
      >
        <template #default="scope">
          <el-tag :type="scope.row.hasSigned === '1' ? 'success' : 'info'">
            {{ scope.row.hasSigned === '1' ? '已签到' : '未签到' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="注册时间"
        align="center"
        key="createTime"
        prop="createTime"
        v-if="columns[6].visible"
        width="160"
      >
        <template #default="scope">
          <span>{{ scope.row.createTime }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="会员状态"
        align="center"
        key="vipValid"
        v-if="columns[7].visible"
        width="120"
      >
        <template #default="scope">
          <el-tag :type="getVipStatusType(scope.row.vipValid)">
            {{ getVipStatusText(scope.row.vipValid) }}
            <template v-if="isVip(scope.row.vipValid)">
              ({{ getVipDays(scope.row.vipValid) }}天)
            </template>
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        label="操作"
        align="center"
        width="70"
        class-name="small-padding fixed-width"
      >
        <template #default="scope">
          <el-tooltip content="下发会员" placement="top">
            <el-button
              link
              type="primary"
              icon="Timer"
              @click="handleAssignMembership(scope.row)"
            ></el-button>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加下发会员对话框 -->
    <el-dialog title="下发会员" v-model="membershipDialog.open" width="500px" append-to-body>
      <el-form :model="membershipForm" :rules="membershipRules" ref="membershipRef" label-width="100px">
        <el-form-item label="会员时长" prop="num">
          <el-radio-group v-model="membershipForm.num">
            <el-radio label="1">1天</el-radio>
            <el-radio label="30">1个月</el-radio>
            <el-radio label="365">1年</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitMembership" :loading="membershipDialog.loading">确 定</el-button>
          <el-button @click="membershipDialog.open = false">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="User">
import { getToken } from "@/utils/auth";
import { userList as getUserList, assignMembership } from "@/api/app/fuser";

const { proxy } = getCurrentInstance();
const { sys_normal_disable, sys_user_sex } = proxy.useDict(
  "sys_normal_disable",
  "sys_user_sex"
);

const userList = ref([]);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const dateRange = ref([]);

// 添加查询参数定义
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  tel: undefined,
  startTime: undefined,
  endTime: undefined
});

// 列显隐信息
const columns = ref([
  { key: 0, label: `编号`, visible: true },
  { key: 1, label: `姓名`, visible: true },
  { key: 2, label: `电话`, visible: true },
  { key: 3, label: `考试代码`, visible: true },
  { key: 4, label: `积分`, visible: true },
  { key: 5, label: `是否签到`, visible: true },
  { key: 6, label: `注册时间`, visible: true },
  { key: 7, label: `会员状态`, visible: true }
]);

/** 查询用户列表 */
function getList() {
  loading.value = true;
  // 如果有日期范围，设置开始和结束时间
  if (dateRange.value && dateRange.value.length === 2) {
    queryParams.value.startTime = dateRange.value[0];
    queryParams.value.endTime = dateRange.value[1];
  } else {
    queryParams.value.startTime = undefined;
    queryParams.value.endTime = undefined;
  }
  
  getUserList(queryParams.value).then(
    (res) => {
      loading.value = false;
      userList.value = res.rows;
      total.value = res.total;
    }
  );
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.startTime = undefined;
  queryParams.value.endTime = undefined;
  proxy.resetForm("queryRef");
  queryParams.value.pageNum = 1;
  handleQuery();
}

/** 下发会员相关数据 */
const membershipDialog = reactive({
  open: false,
  loading: false
});

const membershipForm = reactive({
  userId: undefined,
  num: '1',    // 数量
  unit: '0'    // 单位，默认为0
});

const membershipRules = {
  num: [
    { required: true, message: "请选择会员时长", trigger: "change" }
  ]
};

const membershipRef = ref();

/** 打开下发会员对话框 */
function handleAssignMembership(row) {
  membershipForm.userId = row.id;
  membershipForm.num = '1';  // 重置为默认值
  membershipForm.unit = '0'; // 重置为默认值
  membershipDialog.open = true;
}

/** 提交下发会员 */
function submitMembership() {
  membershipRef.value.validate((valid) => {
    if (valid) {
      membershipDialog.loading = true;
      assignMembership(membershipForm).then(response => {
        proxy.$modal.msgSuccess("下发会员成功");
        membershipDialog.open = false;
        getList();
      }).catch(() => {
        // 处理错误
      }).finally(() => {
        membershipDialog.loading = false;
      });
    }
  });
}

/** 选择条数  */
function handleSelectionChange(selection) {
  // 如果需要多选功能，可以保留这个方法
  // 如果不需要，可以删除这个方法和表格的 @selection-change 事件
}

/** 获取会员状态标签类型 */
function getVipStatusType(vipValid) {
  if (!vipValid) {
    return 'info'  // 未开通
  }
  return new Date(vipValid) > new Date() ? 'success' : 'danger'  // 有效/过期
}

/** 判断是否是有效会员 */
function isVip(vipValid) {
  return vipValid && new Date(vipValid) > new Date()
}

/** 计算会员剩余天数 */
function getVipDays(vipValid) {
  if (!vipValid) return 0
  const today = new Date()
  const validDate = new Date(vipValid)
  const diffTime = validDate.getTime() - today.getTime()
  return Math.ceil(diffTime / (1000 * 60 * 60 * 24))
}

/** 获取会员状态显示文本 */
function getVipStatusText(vipValid) {
  if (!vipValid) {
    return '未开通'
  }
  return new Date(vipValid) > new Date() ? 'VIP' : '已过期'
}

getList();
</script>

```